package com.visense.smart.pharm.mybatis.datasource.core;

import lombok.extern.slf4j.Slf4j;

import javax.sql.DataSource;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.util.logging.Logger;

/**
 * KLIB 的DataSource ,注入到springboot的动态数据源中，与mybatis结合使用。
 * 因为KLIB是加密过的 sqlite数据库，不是标准的jdbc接口的，因此没办法使用druid等来集成。
 * 这里klib 仅查询使用，不考虑事务。
 *    TODO 需要优化getConnection方法，使用连接池
 *
 * @author Juveniless
 * @date 2023-10-17 10:18:32
 */
@Slf4j
public class SqliteDataSource implements DataSource {

    private String name;
    private String url;
    private String password;

    public SqliteDataSource(String name, String url, String password) {
        this.name = name;
        this.url = url;
        this.password = password;
    }

    @Override
    public Connection getConnection() throws SQLException {
        try {
            Connection sqliteConnection = DbConnectManager.getSqliteConnection(url, password);
            return sqliteConnection;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(name + "数据源连接失败" + e.getMessage());
        }
    }


    @Override
    public Connection getConnection(String username, String password) throws SQLException {
        return getConnection();
    }


    @Override
    public <T> T unwrap(Class<T> iface) throws SQLException {
        throw new SQLException(getClass().getName() + " is not a wrapper.");
    }


    @Override
    public boolean isWrapperFor(Class<?> iface) throws SQLException {
        return false;
    }


    @Override
    public PrintWriter getLogWriter() throws SQLException {
        return DriverManager.getLogWriter();
    }

    @Override
    public void setLogWriter(PrintWriter logWriter) throws SQLException {
        DriverManager.setLogWriter(logWriter);
    }

    @Override
    public void setLoginTimeout(int loginTimeout) throws SQLException {
        DriverManager.setLoginTimeout(loginTimeout);
    }

    @Override
    public int getLoginTimeout() throws SQLException {
        return DriverManager.getLoginTimeout();
    }

    @Override
    public Logger getParentLogger() throws SQLFeatureNotSupportedException {
        return Logger.getLogger(Logger.GLOBAL_LOGGER_NAME);
    }
}
